package com.ruoyi.college.controller;

import com.ruoyi.college.domain.Class;
import com.ruoyi.college.domain.College;
import com.ruoyi.college.domain.Major;
import com.ruoyi.college.service.IArchiveService;
import com.ruoyi.college.service.IClassService;
import com.ruoyi.college.service.ICollegeService;
import com.ruoyi.college.service.IMajorService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.DynamicExcelUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.*;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
 * 班级信息Controller
 * 
 * @author ruoyi
 * @date 2025-08-25
 */
@Controller
@RequestMapping("/college/archive")
public class ArchiveController extends BaseController
{
    private String prefix = "college/class";

    @Autowired
    private IClassService classService;

    @Autowired
    private IArchiveService archiveService;

    @Autowired
    private IMajorService majorService;

    @Autowired
    private ICollegeService collegeService;

    @RequiresPermissions("college:archive:view")
    @GetMapping()
    public String cla(ModelMap mmap)
    {
        mmap.put("colleges", collegeService.selectCollegeList(new College()));
        mmap.put("majors", majorService.selectMajorList(new Major()));
        return prefix + "/archive";
    }

    /**
     * 查询班级信息列表
     */
    @RequiresPermissions("college:archive:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Class cla)
    {
        startPage();
        List<Class> list = classService.selectClassList(cla);
        return getDataTable(list);
    }

    /**
     * 导出班级信息列表
     */
    @RequiresPermissions("college:archive:export")
    @Log(title = "班级信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public ResponseEntity<byte[]> export(Class cla) throws IOException
    {


        List<Map<String, Object>> list = archiveService.getStudentScorePivot(cla);


// 1. 动态生成Excel
        List<String> title =  new ArrayList<>();
        Map<String, Object> rowHeader = list.get(0);
        List<Map<String, Object>> data = new ArrayList<>();
        for (String key : rowHeader.keySet()) {
            System.out.println("键：" + key);
            title.add(key);
        }
        for (Map<String, Object> row : list)
        {
            data.add( row);
        }

        // 更多数据...
        ByteArrayInputStream excelStream = DynamicExcelUtil.generateExcel(title, data);

        // 2. 获取已有的PDF文件（示例：从classpath读取）
        // 实际场景可能从数据库/BLOB字段或文件服务器获取

        List<Map<String, Object>> projects = archiveService.selectProjectsByClassId(cla.getClassId());
        List<Map<String, Object>> result = new ArrayList<>();





        InputStream pdfStream1 = null;
//        InputStream pdfStream2 = new ClassPathResource("static/file2.pdf").getInputStream();

        // 3. 打包成ZIP
        try (ByteArrayOutputStream zipOut = new ByteArrayOutputStream();
             ZipArchiveOutputStream zipArchive = new ZipArchiveOutputStream(zipOut)) {


            for (Map<String, Object> project : projects) {

                BigInteger id = (BigInteger) project.get("project_id");
                Long projectId = id.longValue();  // 安全转换
                String projectName = (String) project.get("project_name");
                result = archiveService.selectStudentScoreProject(projectId,cla.getClassId());
                for (Map<String, Object> row : result)
                {

                    String studentNo = (String) row.get("studentNo");
                    String name = (String) row.get("name");

                    String path =projectName+"/"+name+"-"+studentNo+".pdf";
                    String filePath = (String) row.get("filePath");
                    pdfStream1 = new ClassPathResource(filePath).getInputStream();
                    addToZip(zipArchive, pdfStream1, path);
                    row.put("project_id", projectId);
                }

            }




            // 添加Excel到ZIP
            addToZip(zipArchive, excelStream, "动态数据.xlsx");
            // 添加PDF到ZIP
//            addToZip(zipArchive, pdfStream1, "合同文件/文档1.pdf");
//            addToZip(zipArchive, pdfStream2, "证明材料/文档2.pdf");
            zipArchive.finish();
            byte[] zipBytes = zipOut.toByteArray();
            // 4. 设置响应头，返回ZIP文件
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=\"files.zip\"");
            headers.add("Content-Type", "application/zip");

            return new ResponseEntity<>(zipBytes, headers, HttpStatus.OK);
        } finally {
            // 关闭流
            excelStream.close();
            pdfStream1.close();
//            pdfStream2.close();
        }





    }



    /**
     * 将输入流添加到ZIP归档
     */
    private void addToZip(ZipArchiveOutputStream zipArchive, InputStream stream, String fileName) throws IOException {
        ZipArchiveEntry entry = new ZipArchiveEntry(fileName);
        zipArchive.putArchiveEntry(entry);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = stream.read(buffer)) != -1) {
            zipArchive.write(buffer, 0, len);
        }
        zipArchive.closeArchiveEntry();
    }



}
